package com.echo.week;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author echo
 * @Description Semaphore 信号量案例--抢车位
 * @Date 2023/10/20.
 * @Version 1.0
 */
public class DemoSemaphore {
    public static void main(String[] args) {

        //一共三个车位【限流使用】
        Semaphore semaphore = new Semaphore(3);

        for (int i =1;i<=6;i++){
            new Thread(()->{
                try {
                    semaphore.acquire(); //抢占车位
                    System.out.println(Thread.currentThread().getName()+"\t抢到了车位！");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+"\t停车结束，离开车位！");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    semaphore.release();//释放车位
                }
            },"Thread-Car"+String.valueOf(i)).start();

        }
    }
}
